// pages/reports/reports.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    members: [],
    selectedMemberId: null,
    reportTypes: ['体检报告', '检查报告', '诊断报告', '用药记录', '其他'],
    selectedType: '全部',
    reports: [],
    filteredReports: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 检查登录状态
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.loadMembers();
    this.loadReports();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时刷新数据
    this.loadReports();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  loadMembers: function () {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 从服务器获取家庭成员数据
    wx.request({
      url: 'http://localhost:3000/api/members',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({
            members: res.data.data.members || []
          });
        } else {
          console.error('获取家庭成员失败:', res.data.message);
          wx.showToast({
            title: res.data.message || '获取成员数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  loadReports: function () {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    // 从服务器获取健康报告数据
    wx.request({
      url: 'http://localhost:3000/api/reports',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const reports = res.data.data.reports || [];
          
          // 确保每条报告都有memberName
          const processedReports = reports.map(report => ({
            ...report,
            memberName: report.member ? report.member.name : '未知成员',
            memberAvatar: report.member ? report.member.avatar : ''
          }));
          
          this.setData({
            reports: processedReports,
            filteredReports: processedReports,
            loading: false
          });
          
          // 应用当前筛选条件
          this.filterReports();
        } else {
          console.error('获取健康报告失败:', res.data.message);
          this.setData({ loading: false });
          wx.showToast({
            title: res.data.message || '获取报告失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  selectMember: function (e) {
    const memberId = e.currentTarget.dataset.id;
    
    // 如果点击的是当前选中的成员，则取消选择
    const newSelectedId = memberId === this.data.selectedMemberId ? null : memberId;
    
    this.setData({
      selectedMemberId: newSelectedId
    });
    
    this.filterReports();
  },

  selectType: function (e) {
    const type = e.currentTarget.dataset.type;
    
    this.setData({
      selectedType: type
    });
    
    this.filterReports();
  },

  filterReports: function () {
    const { reports, selectedMemberId, selectedType } = this.data;
    
    let filtered = reports;
    
    if (selectedMemberId !== null) {
      filtered = filtered.filter(report => report.member_id === selectedMemberId || report.memberId === selectedMemberId);
    }
    
    if (selectedType !== '全部') {
      filtered = filtered.filter(report => report.type === selectedType);
    }
    
    this.setData({
      filteredReports: filtered
    });
  },

  addReport: function () {
    wx.navigateTo({
      url: '/pages/reports/add/add'
    });
  },

  viewReportDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/reports/detail/detail?id=${id}`
    });
  },

  shareReport: function (e) {
    const id = e.currentTarget.dataset.id;
    const report = this.data.reports.find(r => r.id === id);
    
    if (report) {
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      });
    }
  },

  deleteReport: function (e) {
    const id = e.currentTarget.dataset.id;
    const report = this.data.reports.find(r => r.id === id);
    
    if (report) {
      wx.showModal({
        title: '确认删除',
        content: `确定要删除"${report.title}"报告吗？`,
        success: (res) => {
          if (res.confirm) {
            const token = wx.getStorageSync('token');
            
            wx.request({
              url: `http://localhost:3000/api/reports/${id}`,
              method: 'DELETE',
              header: {
                'Authorization': `Bearer ${token}`
              },
              success: (res) => {
                if (res.data.success) {
                  wx.showToast({
                    title: '删除成功',
                    icon: 'success'
                  });
                  
                  // 重新加载报告列表
                  this.loadReports();
                } else {
                  wx.showToast({
                    title: res.data.message || '删除失败',
                    icon: 'none'
                  });
                }
              },
              fail: (err) => {
                console.error('请求失败:', err);
                wx.showToast({
                  title: '网络错误，请稍后重试',
                  icon: 'none'
                });
              }
            });
          }
        }
      });
    }
  }
})